<template>
  <div class="scene" ref="sceneDiv"></div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import scene from '@/three/scene'
import cameraModule from '@/three/camera'
import rendererModule from '@/three/renderer'
import axesHelper from '@/three/axesHelper'
import controlModule from '@/three/controls'
import animate from '@/three/animate'
import createMesh from '@/three/createMesh'
import '@/three/init'

import AlarmSprite from "@/three/mesh/AlarmSprite";
import LightWall from "@/three/mesh/LightWall";
import FlyLineShader from "@/three/mesh/FlyLineShader";
import LightRadar from "@/three/mesh/LightRadar";

import gsap from 'gsap'
import eventBus from '@/utils/eventBus'

const props = defineProps(['eventList'])

// 场景元素div
let sceneDiv = ref(null)
// 添加相机
scene.add(cameraModule.activeCamera)
// 添加辅助坐标轴
scene.add(axesHelper)
// 创建物体
createMesh()

onMounted(() => {
  sceneDiv.value.appendChild(rendererModule.renderer.domElement)
  animate()
})

const eventListMesh = [];
let mapFn = {
  '火警': (position, i) => {
    const lightWall = new LightWall(1, 2, position)
    lightWall.eventListIndex = i
    scene.add(lightWall.mesh)
    eventListMesh.push(lightWall)
  },
  '治安': (position, i) => {
    // 生成随机颜色
    /* const color = new THREE.Color(
      Math.random(),
      Math.random(),
      Math.random()
    ).getHex(); */
    // 添加着色器飞线
    const flyLineShader = new FlyLineShader(position)
    flyLineShader.eventListIndex = i
    scene.add(flyLineShader.mesh)
    eventListMesh.push(flyLineShader)
  },
  '电力': (position, i) => {
    // 添加雷达
    const lightRadar = new LightRadar(2, position)
    lightRadar.eventListIndex = i
    scene.add(lightRadar.mesh)
    eventListMesh.push(lightRadar)
  }
}

eventBus.on('eventToggle', i => {
  eventListMesh.forEach(item => {
    if(item.eventListIndex === i) {
      item.mesh.visible = true
    } else {
      item.mesh.visible = false
    }
  });

  const position = {
    x: props.eventList[i].position.x / 5 - 10,
    y: 0,
    z: props.eventList[i].position.y / 5 - 10,
  };

  // 控制器移到该物体
  gsap.to(controlModule.controls.target, {
    duration: 1,
    x: position.x,
    y: position.y,
    z: position.z
  })
})

watch(() => props.eventList, (val) => {
  eventListMesh.forEach(item => {
    item.remove()
  });

  val.forEach((item, i) => {
    const position = {
      x: item.position.x / 5 - 10,
      z: item.position.y / 5 - 10
    };

    const alarmSprite = new AlarmSprite(item.name, position)
    alarmSprite.onClick(() => {
      eventBus.emit('spriteClick', { event: item, i })
    })
    alarmSprite.eventListIndex = i
    eventListMesh.push(alarmSprite)
    scene.add(alarmSprite.mesh)

    if(mapFn[item.name]) {
      mapFn[item.name](position, i)
    }
  })
})
</script>

<style lang="less" scoped>
.scene {
  width: 100vw;
  height: 100vh;
  position: fixed;
  z-index: 100;
  left: 0;
  top: 0;
}
</style>